package visaoInterface;

import dao.DaoLocacao;
import dao.DaoPessoa;
import dao.DaoTipoVeiculo;
import dao.DaoVeiculo;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.dominio.Locacao;
import modelo.dominio.TipoVeiculo;
import modelo.dominio.Veiculo;

public class FinalizarLocacao extends javax.swing.JDialog {

    /** Creates new form FinalizarLocacao */
    public FinalizarLocacao(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    DefaultTableModel tmLocacoesDisponiveis = new DefaultTableModel(null, new String[]{"Codigo da Locação","Cliente","Veiculo","Data da Locação","Km Saída"} ) {
    @Override
    public boolean isCellEditable(int row, int col){
         return false;
      } 
    };
    
    /**
     * mostra na tabela as locações disponiveis.
     * @param locacoes vetor das locações disponiveis.
     */
    public void mostraLocacoesDisponiveis(Vector<Locacao> locacoes){
        String[] linha = new String[] {null,null,null,null,null};
        //limpa a tabel
        while(tmLocacoesDisponiveis.getRowCount()>0){
            tmLocacoesDisponiveis.removeRow(0);
        }
        DaoPessoa dp = new DaoPessoa();
        DaoVeiculo dv = new DaoVeiculo();
        //exibe na tabela
        for (int i=0 ; i<locacoes.size() ; i++) {
         tmLocacoesDisponiveis.addRow(linha);
         tmLocacoesDisponiveis.setValueAt(locacoes.get(i).getIdLocacao(),i,0);
         tmLocacoesDisponiveis.setValueAt(dp.buscarClienteCod(locacoes.get(i).getCodCliente()).getNome(),i,1);
         tmLocacoesDisponiveis.setValueAt(dv.buscarObjetoPorCod(locacoes.get(i).getCodVeiculo()).getModelo(),i,2);
         tmLocacoesDisponiveis.setValueAt(locacoes.get(i).getDataSaida(),i,3);
         tmLocacoesDisponiveis.setValueAt(dv.buscarObjetoPorCod(locacoes.get(i).getCodVeiculo()).getKmAtual(),i,4);
        }  
        if (tmLocacoesDisponiveis.getRowCount() == 0){
            JOptionPane.showMessageDialog(null, "Registro nao encontrados.");
        }
    }
    
    public void colocaComboBoxResultados(Vector<Locacao> locacoes){
        for (int i=0 ; i<locacoes.size() ; i++) {
            jCResultados.addItem(locacoes.get(i).getIdLocacao());
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTTabela = new javax.swing.JTable();
        jLTitulo = new javax.swing.JLabel();
        jLLocacoes = new javax.swing.JLabel();
        jTChegada = new javax.swing.JTextField();
        jTData = new javax.swing.JTextField();
        jLInserir = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLData = new javax.swing.JLabel();
        jLObter = new javax.swing.JLabel();
        jBValor = new javax.swing.JButton();
        jTValor = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jCResultados = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jBObter = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTTabela.setModel(tmLocacoesDisponiveis);
        jTTabela.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTTabelaPropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(jTTabela);

        jLTitulo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLTitulo.setText("Finalizar Locacações");

        jLLocacoes.setText("Locações Abertas:");

        jTChegada.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTChegadaActionPerformed(evt);
            }
        });

        jLInserir.setText("Inserir:");

        jLabel4.setText("Km de Chegada");

        jLData.setText("Data da Chegada");

        jLObter.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLObter.setText("Obter valor da locação");

        jBValor.setText("FINALIZAR");
        jBValor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBValorActionPerformed(evt);
            }
        });

        jTValor.setEditable(false);

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel7.setText("R$");

        jLabel1.setText("Selecione o código da locação a ser finalizada:");

        jCResultados.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jButton1.setText("Data Atual");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jBObter.setText("Obter");
        jBObter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBObterActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLInserir, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(1213, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLLocacoes, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 882, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(62, 62, 62)
                                        .addComponent(jLObter, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(24, 24, 24)
                                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(jTChegada, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                .addComponent(jBObter, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(jTValor, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)))))
                                .addGap(105, 105, 105)
                                .addComponent(jLData, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(58, 58, 58)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jBValor, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTData, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(360, 360, 360))))
            .addGroup(layout.createSequentialGroup()
                .addGap(288, 288, 288)
                .addComponent(jLTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCResultados, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(450, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(41, 41, 41)
                        .addComponent(jLTitulo)
                        .addGap(18, 18, 18)
                        .addComponent(jLLocacoes))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCResultados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLInserir))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTChegada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)
                            .addComponent(jLData)
                            .addComponent(jTData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLObter)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTValor, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jBObter)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                        .addComponent(jBValor, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(44, 44, 44))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    Vector<Locacao> locacoes;
    Vector<Veiculo> veiculos;
    double resultado = 0;
private void jTChegadaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTChegadaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTChegadaActionPerformed

private void jBValorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBValorActionPerformed
        DaoLocacao dl = new DaoLocacao();
        DaoVeiculo dv = new DaoVeiculo();
        DaoTipoVeiculo dtv = new DaoTipoVeiculo();
        Locacao l = new Locacao();
        Veiculo v = new Veiculo();
        TipoVeiculo tv = new TipoVeiculo();
        l = dl.buscarLocacaoPorCod(Integer.parseInt(jCResultados.getSelectedItem().toString()));
        v = dv.buscarObjetoPorCod(l.getCodVeiculo());
        tv = dtv.buscarObjetoPorCod(v.getCodTipoVeiculo());
        l.setValor(resultado);
        dl.atualizar(l);
        v.setSomaLocacoes(v.getSomaLocacoes() + l.getValor());
        v.setKmAtual(Double.parseDouble(jTChegada.getText()));
        dv.atualizarVeiculoPorLocacao(l,v);
        JOptionPane.showMessageDialog(null, "Locação finalizada com sucesso.");
        dispose();
}//GEN-LAST:event_jBValorActionPerformed

private void jTTabelaPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTTabelaPropertyChange
    DaoLocacao dl = new DaoLocacao();    
    this.mostraLocacoesDisponiveis(dl.buscarLocacoesDisponiveis());
    this.jCResultados.removeAllItems();
    this.colocaComboBoxResultados(dl.buscarLocacoesDisponiveis());
}//GEN-LAST:event_jTTabelaPropertyChange

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String data = (new java.text.SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date(System.currentTimeMillis())));
        jTData.setText(data);
}//GEN-LAST:event_jButton1ActionPerformed

private void jBObterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBObterActionPerformed
        DaoLocacao dl = new DaoLocacao();
        DaoVeiculo dv = new DaoVeiculo();
        DaoTipoVeiculo dtv = new DaoTipoVeiculo();
        Locacao l = new Locacao();
        Veiculo v = new Veiculo();
        TipoVeiculo tv = new TipoVeiculo();
        
   if (jTChegada.getText().equals("")) {
       JOptionPane.showMessageDialog(null, "Favor inserir valor do KM chegada.");
   } else {
        l = dl.buscarLocacaoPorCod(Integer.parseInt(jCResultados.getSelectedItem().toString()));
        v = dv.buscarObjetoPorCod(l.getCodVeiculo());
        tv = dtv.buscarObjetoPorCod(v.getCodTipoVeiculo());
        if ((Integer.parseInt(jTChegada.getText())) >= (v.getKmAtual())) {
            if (l.getTipolocacao().equals("Por Quilometragem")) {
                resultado = ((Double.parseDouble(jTChegada.getText().toString()) - l.getKmSaida())* tv.getPrecoKm()) + tv.getTaxaBase();
            }
            if (l.getTipolocacao().equals("Quilometragem Livre")) {
                resultado = (tv.getTaxaBase() * l.getPrevDias());
            }
            this.jTValor.setText(String.valueOf(resultado));
        } else {
            JOptionPane.showMessageDialog(null, "O quilometragem de entrada inserida é menor que a de saída.");
        }
   } 

}//GEN-LAST:event_jBObterActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FinalizarLocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FinalizarLocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FinalizarLocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FinalizarLocacao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FinalizarLocacao dialog = new FinalizarLocacao(new javax.swing.JDialog(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBObter;
    private javax.swing.JButton jBValor;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jCResultados;
    private javax.swing.JLabel jLData;
    private javax.swing.JLabel jLInserir;
    private javax.swing.JLabel jLLocacoes;
    private javax.swing.JLabel jLObter;
    private javax.swing.JLabel jLTitulo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTChegada;
    private javax.swing.JTextField jTData;
    private javax.swing.JTable jTTabela;
    private javax.swing.JTextField jTValor;
    // End of variables declaration//GEN-END:variables
}